import plugin from '../../lib/plugins/plugin.js'
import cfg from '../../lib/config/config.js'

const direction = "使用方法：\n一条消息的格式为【@一名群友+ta的发言内容】。可叠加多条消息，示例：\n\n" +
  "伪造消息@甲这是甲说的话@乙这是乙说的第一句话|这是乙说的第二句话@丙这是丙发送的图片\n\n" +
  "另外，@群友，可用|^qq号|代替"  

export class Fakemessage extends plugin {
  constructor() {
    super({
      /** 功能名称 */
      name: '伪造消息',
      /** 功能描述 */
      dsc: '真的不是我说的！',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 5000,
      rule: [
        {
          /** 命令正则匹配 */
          reg: "^#伪造消息([\\s\\S]*)$",  
          /** 执行方法 */
          fnc: 'Fakemessage'
        }
      ]
    })
  }
  
  async Fakemessage(e) {
    let rawmsg = e.message;
    // 获取当前群配置
    let conf = cfg.getGroup(this.group_id);
    if (conf.onlyReplyAt && rawmsg[0].type == "at" && rawmsg[0].qq == cfg.qq) {
      rawmsg.splice(0, 1);
    }

    // 处理消息
	let msgtxt
    for (let val of conf.botAlias) {
      var regBotName = new RegExp(val + "#*＃*伪造消息");
	  msgtxt = rawmsg[0].type == 'long_msg' ? rawmsg[1] : rawmsg[0]
      msgtxt.text = msgtxt.text.replace(regBotName, "");
    }
    msgtxt.text = msgtxt.text.replace(/#*＃*伪造消息/, "");

    let regExpQQ = /(\^|＾)\d{5,10}/g
    let regBrief = /(\^|＾)b.+/g
    let regPrompt = /(\^|＾)p.+/g
    let regTitle = /(\^|＾)t.+/g
    let regSummary = /(\^|＾)s.+/g

    // let resqq = regExpQQ.exec(rawmsg[0].text);
    let isqq = regExpQQ.test(msgtxt.text);
    console.log("isqq", isqq);

    if (!e.at && !isqq) {
      e.reply([segment.text(direction)]);//没有@则提示
      return true;
    }

    let qq = null
    let name = ""
    var data_msg = []//存放消息

    // 对e.message中的成员逐个处理：
	let timestamp = Math.floor(Date.now() / 1000)
    for (let i = 0; i < rawmsg.length; i++) {
      // 如果是at类型，就把其中的qq号和昵称取出来
      if (rawmsg[i].type == "at") {
        qq = rawmsg[i].qq;
        name = rawmsg[i].text.replace(/@/g, "");
        continue;
      }
      // 如果是text类型
      else if (rawmsg[i].type == "text") {
        if (rawmsg[i].text == "") {
          continue;
        }
        // 将其中的text用split分割成数组，逐一push进data_msg
        let txt = (rawmsg[i].text).trim().split("|");
        for (let val of txt) {
          let resqq = val.match(regExpQQ);
          if (resqq) {
            qq = resqq[0].substring(1) * 1;
            name = await this.getname(qq, e);
            continue;
          }
          if (!qq) {
            e.reply(direction);
            return true;
          }
          if (val != "") {
			let random_delay = Math.floor(Math.random() * 61);
                timestamp += random_delay;
            data_msg.push({
              message: val,
              nickname: name,
              user_id: qq,
			  time: timestamp
            });
          }
        }
      }
      // 如果是image类型，取其中的url，push进data_msg
      else if (rawmsg[i].type == "image") {
		let random_delay = Math.floor(Math.random() * 61);
            timestamp += random_delay;
        data_msg.push({
          message: segment.image(rawmsg[i].url),
          nickname: name,
          user_id: qq,
		  time: timestamp
        });
      }
      else {
        logger.error("【伪造消息】出现了预设之外的类型：", rawmsg[i].type);
      }
    }

    if (data_msg == []) {
      e.reply([segment.text(direction)]);
      return true;
    }

    // 制作成合并消息
    let ForwardMsg;
    /** 制作转发内容 */
    if (this.e?.group?.makeForwardMsg) {
      ForwardMsg = await e.group.makeForwardMsg(data_msg);
    } else if (this.e?.friend?.makeForwardMsg) {
      ForwardMsg = await e.friend.makeForwardMsg(data_msg);
    } else {
      return msg.join('\n')
    }
    
    await e.reply(ForwardMsg)//回复消息
    return true //返回true 阻挡消息不再往下
  }

  // 获取QQ的昵称
  async getname(qq, e) {
    let name;
    if (e.isGroup) {
        try {
            let member = await e.group.pickMember(qq).getInfo();
            name = member.card || member.nickname || ''
        } catch(error) {
            let member = await Bot.pickUser(qq).getInfo()
            name = member.nickname || ''
        }
        if (!name) name = qq
    }
    return name;
  }
}